package com.mingke.java.AIO;

import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author mingke
 * @function AIO外设连接成功的回调
 * @date 2021/11/9
 */
public class AIOAcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {

    @Override
    public void completed(AsynchronousSocketChannel socketChannel, AsynchronousServerSocketChannel attachment) {
        try {
            //设置TCP的参数，作用目前为止不知道
            socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
            socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
            socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
            //设置读取数据的回调
            if(socketChannel.isOpen()) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                byteBuffer.clear();
                socketChannel.read(byteBuffer, byteBuffer, new AIOReadHandler());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //让服务器继续接受其他请求
            attachment.accept(attachment, this);
        }
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
        System.out.println("监听失败了");
        try {
            exc.printStackTrace();
        }finally {
            //让服务器继续接受其他请求
            attachment.accept(attachment, this);
        }
    }
}
